package cn.fl.project.controller;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.condition.CapFundQueryCondition;
import cn.fl.capital.constant.CapitalConstant;
import cn.fl.capital.constant.SettleConstant;
import cn.fl.capital.constant.ZGSettleScheduleEnum;
import cn.fl.capital.dto.CapCstStmScheduleDTO;
import cn.fl.capital.service.ICapFundService;
import cn.fl.capital.vo.CapFundVO;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.insurance.constant.InsuranceConstant;
import cn.fl.project.condition.PrjPrdDtlQueryCondition;
import cn.fl.project.condition.PrjPrdPaySchMQueryCondition;
import cn.fl.project.constant.PrjPrdPaySchMConstant;
import cn.fl.project.dto.PrjPrdPaySchDDTO;
import cn.fl.project.dto.PrjPrdPaySchMDTO;
import cn.fl.project.dto.PrjPrdPrpsFeeDetailDTO;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.project.service.IPrjPrdDtlService;
import cn.fl.project.service.IPrjPrdPaySchMApiService;
import cn.fl.project.service.IPrjPrdPaySchMService;
import cn.fl.project.service.IPrjSettleOfFinInstService;
import cn.fl.project.vo.PrjBscInfoVO;
import cn.fl.project.vo.PrjPrdDtlVO;
import cn.fl.project.vo.PrjPrdPaySchDVO;
import cn.fl.project.vo.PrjPrdPaySchMVO;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.vo.SysDictionaryVO;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @Description: 金融机构（资管项目）结清controller
 * @Author: liurong
 * @CreateDate: 2019/5/13 10:37
 * @Version: 1.0
 */
@Controller
@RequestMapping("/project/financialInst")
public class PrjSettleOfFinancialInstitutionController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(PrjSettleOfFinancialInstitutionController.class);

    @Autowired
    private IPrjSettleOfFinInstService prjSettleOfFinInstService;
    @Autowired
    private IPrjBscInfoService prjBscInfoService;
    @Autowired
    private IPrjPrdPaySchMService prjPrdPaySchMService;
    @Autowired
    private IPrjPrdDtlService prjPrdDtlService;
    @Autowired
    private ICapFundService capFundService;
    @Autowired
    private ICstBscInfoService cstBscInfoService;
    @Autowired
    private IPrjPrdPaySchMApiService prjPrdPaySchMApiService;

    /**
     * 结清申请限制条件校验
     *
     * @param request
     * @throws
     * @author liurong
     * @returnC
     * @date 2019/5/13 10:40
     */
    @RequestMapping(value = "/checkApplyConstraints.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO checkApplyConstraints(HttpServletRequest request) throws BaseException {
        DataResultVO resultVO = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        String paySchId = request.getParameter("paySchId");
        String settleType = request.getParameter("settleType");
        try {
            if (StringUtils.isEmpty(paySchId)) {
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "支付表ID不能为空！");
            }

            prjSettleOfFinInstService.checkApplyConstraints(Long.parseLong(paySchId), settleType);
        } catch (BaseException e) {
            resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            resultVO.setInfo(e.getMessage());
        } catch (Exception e) {
            resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            resultVO.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
        }
        return resultVO;
    }

    /**
     * 进入资管结清选择期数页面
     *
     * @param request
     * @return
     * @throws BaseException
     */
    @RequestMapping(value = "/showChooseSettlePdPage.do", method = {RequestMethod.GET})
    public ModelAndView showChooseSettlePdPage(HttpServletRequest request) throws BaseException {
        String prjId = request.getParameter("prjId");
        // 结清方式：1-正常结清  2-提前结清
        String settleTyp = request.getParameter("settleType");
        String settleTypNm = "";
        if (SettleConstant.CODE_SETT_TYPE_NORMAL.equals(settleTyp)) {
            settleTypNm = "正常结清";
        } else if (SettleConstant.CODE_SETT_TYPE_ADVANCE.equals(settleTyp)) {
            settleTypNm = "提前结清";
        }

        PrjPrdPaySchMQueryCondition prjPrdPaySchMQueryCondition = new PrjPrdPaySchMQueryCondition();
        prjPrdPaySchMQueryCondition.setPrjId(Long.valueOf(prjId));
        prjPrdPaySchMQueryCondition.setIsAllBiz(BaseConstant.IS_YESNO_YES);
        List<PrjPrdPaySchMVO> prjPrdPaySchMVOS = prjPrdPaySchMService.searchList(prjPrdPaySchMQueryCondition);
        if (CollectionUtils.isEmpty(prjPrdPaySchMVOS)) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, "支付表数据不存在！");
        }
        // 资方支付表 1
        PrjPrdPaySchMVO instPaySchMVO = new PrjPrdPaySchMVO();
        // 我司支付表列表 N
        List<PrjPrdPaySchMVO> ourCompanyPaySchMVOS = Lists.newArrayListWithCapacity(prjPrdPaySchMVOS.size() - 1);
        for (PrjPrdPaySchMVO prjPrdPaySchMVO : prjPrdPaySchMVOS) {
            if (prjPrdPaySchMVO.getIsSqBiz() == BaseConstant.IS_YESNO_YES) {
                if (PrjPrdPaySchMConstant.PAY_SCH_TYP_CD_WS.equals(prjPrdPaySchMVO.getPaySchTypCd())) {
                    ourCompanyPaySchMVOS.add(prjPrdPaySchMVO);
                }
            } else {
                instPaySchMVO = prjPrdPaySchMVO;
            }
        }
        // 校验是否支持资管结清
        prjSettleOfFinInstService.isSupport(instPaySchMVO.getBizFlag());

        PrjBscInfoVO prj = null;
        if (StringUtils.isNotBlank(prjId)) {
            prj = this.prjBscInfoService.selectById(Long.valueOf(prjId));
        }
        Integer startLsPd = prjSettleOfFinInstService.getStartSettlePd(instPaySchMVO.getId());
        ModelAndView view = new ModelAndView("project/settleOfFinaInst/settleChoosePd");
        view.addObject("payPd", instPaySchMVO.getLsPd());
        view.addObject("startLsPd", startLsPd);
        view.addObject("prj", prj);
        view.addObject("ourCompanyPaySchList", ourCompanyPaySchMVOS);
        view.addObject("instPaySch", instPaySchMVO);
        view.addObject("settleTyp", settleTyp);
        view.addObject("settleTypNm", settleTypNm);
        return view;
    }

    /**
     * 结清申请详情页面，流程中附加页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/showZGSettlePage.do", method = {RequestMethod.GET})
    public ModelAndView showZGSettlePage(HttpServletRequest request) {
        String taskDefKey = request.getParameter("taskDefKey");// 流程节点key
        String pInstId = request.getParameter("processInstanceId");// 流程实例ID

        String prjIdStr = request.getParameter("prjId");//项目ID
        String paySchIdStr = request.getParameter("paySchId");// 支付表ID
        String settlePd = request.getParameter("settlePd");//结清期次
        String settleTyp = request.getParameter("settleTyp");//结清类型1-正常  2-提前

        // 结清账户信息标志，格式：0-0-0-0，每位取值说明：0~隐藏；1~只读；2~可编辑；
        // 说明：index(0)：客户付款账户；  index(1)：客户收款账户；  index(2)：我司付款账户；  index(3)：我司收款账户；
        String bankAct = request.getParameter("bankAct");
        String confirm = request.getParameter("confirm");

        ModelAndView view = new ModelAndView("project/settleOfFinaInst/settleCalcDataPage");
        ListPageVO<PrjPrdPaySchDDTO> feeListPage = null;
        ListPageVO<PrjPrdPrpsFeeDetailDTO> listPage = null;
        try {
            Integer settleStartPd = null;
            if (StringUtils.isNotEmpty(settlePd)) {
                settleStartPd = Integer.parseInt(settlePd);
            }
            Long prjId = StringUtils.isEmpty(prjIdStr) ? null : Long.valueOf(prjIdStr);
            Long paySchId = StringUtils.isEmpty(paySchIdStr) ? null : Long.valueOf(paySchIdStr);

            PrjPrdPaySchMDTO pay = prjSettleOfFinInstService.getCalculateSettleData(prjId, paySchId, settleStartPd, settleTyp);
            settleTyp = pay.getSettleType();

            feeListPage = new ListPageVO<>(pay.getFeeDetailList(), pay.getFeeDetailList().size());
            if (SettleConstant.CODE_SETT_TYPE_ADVANCE.equals(pay.getSettleType())) {
                listPage = new ListPageVO<PrjPrdPrpsFeeDetailDTO>(pay.getPrjPrdPayDetailList(), pay.getPrjPrdPayDetailList().size());
                view.addObject("listPage", JSON.toJSONString(listPage));
            }

            List<SysDictionaryVO> settFeeTypCdListJSON = this.prjPrdPaySchMService.getSettFeeTypList();
            if (prjId == null && paySchId != null) {
                // 此情况代表流程中过来的请求
                view.addObject("flow", BaseConstant.IS_YESNO_YES);

                view.addObject("isHaveInterface", prjSettleOfFinInstService.isHaveInterface(pay.getBizFlag()));
            }
            view.addObject("prj", pay.getPrjBscInfoDTO());
            view.addObject("feeListPage", JSON.toJSONString(feeListPage));
            view.addObject("subFeeAmtTotalList", JSON.toJSONString(pay.getSubFeeAmtTotalList()));
            view.addObject("settFeeTypCdListJSON", JSON.toJSONString(settFeeTypCdListJSON));
            view.addObject("settleTyp", settleTyp);
            view.addObject("settleTypNm", SettleConstant.CODE_SETT_TYPE_NORMAL.equals(settleTyp) ? "正常结清" : "提前结清");
            view.addObject("taskDefKey", taskDefKey);
            view.addObject("pInstId", pInstId);
            view.addObject("bankAct", bankAct);
            view.addObject("confirm", confirm);
            view.addObject("fileAuth", request.getParameter("fileAuth"));
            // 将已经add的数据置为null，防止重复传输数据
            pay.setPrjBscInfoDTO(null);
            pay.setFeeDetailList(null);
            pay.setSubFeeAmtTotalList(null);
            view.addObject("pay", pay);
        } catch (BaseException ex) {
            BaseLogUtils.error(logger, "showZGSettlePage", "显示资管结清详情页面查询失败.DATA:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName(), ex);
            throw ex;
        } catch (Exception ex) {
            BaseLogUtils.error(logger, "showZGSettlePage", "显示资管结清详情页面查询失败.DATA:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName(), ex);
            throw ex;
        }
        return view;
    }

    /**
     * 进入支付表详情页面
     *
     * @param request
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "/enterPaySchDetailPage.do", method = {RequestMethod.GET})
    public String enterPaySchDetailPage(HttpServletRequest request, RedirectAttributes redirectAttributes) {
        String url = "redirect:/project/prjprdpayschm/toAddPage.do";
        try {
            String paySchId = request.getParameter("paySchId");
            String prjId = request.getParameter("prjId");

            String prjPrdDtlId = "";
            String prjPrdId = "";

            PrjPrdDtlQueryCondition prjPrdDtlQueryCondition = new PrjPrdDtlQueryCondition();
            prjPrdDtlQueryCondition.setPrjId(Long.parseLong(prjId));
            prjPrdDtlQueryCondition.setPaySchId(Long.parseLong(paySchId));
            PrjPrdDtlVO prjPrdDtlVO = prjPrdDtlService.selectOneByCondition(prjPrdDtlQueryCondition);
            if (prjPrdDtlVO != null) {
                prjPrdDtlId = prjPrdDtlVO.getId().toString();
                prjPrdId = prjPrdDtlVO.getPrjPrdId().toString();
            }
            redirectAttributes.addAttribute("prjId", prjId);
            redirectAttributes.addAttribute("id", paySchId);
            redirectAttributes.addAttribute("prjPrdDtlId", prjPrdDtlId);
            redirectAttributes.addAttribute("prjPrdId", prjPrdId);
            redirectAttributes.addAttribute("detailFlag", true);
        } catch (BaseException e) {
            BaseLogUtils.error(logger, "enterPaySchDetailPage", "进入支付表详情页面", CurrentThreadContext.getCurrentUserName(), e);
        } catch (Exception e) {
            BaseLogUtils.error(logger, "enterPaySchDetailPage", "进入支付表详情页面", CurrentThreadContext.getCurrentUserName(), e);
        }
        return url;
    }

    /**
     * 资金部维护我司与资方结清金额
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/modifyStlAmtOther.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object modifyStlAmtOther(HttpServletRequest request) {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        try {
            String id = request.getParameter("scheduleId");
            String rentAmt = request.getParameter("rentAmt");
            String principalAmt = request.getParameter("principalAmt");
            String interestAmt = request.getParameter("interestAmt");

            CapCstStmScheduleDTO record = new CapCstStmScheduleDTO();
            try {
                record.setRentAmt(DecimalUtils.convertYuanToFen(Double.valueOf(rentAmt)));
                record.setPrincipalAmt(DecimalUtils.convertYuanToFen(Double.valueOf(principalAmt)));
                record.setInterestAmt(DecimalUtils.convertYuanToFen(Double.valueOf(interestAmt)));
            } catch (NumberFormatException e) {
                throw new BaseException("NumberFormatException");
            }
            if (StringUtils.isEmpty(id)) {
                // 新增
                String scheduleCd = request.getParameter("scheduleCd");
                if (StringUtils.isEmpty(scheduleCd)) {
                    throw new BaseException("申请进度CD不能为空！");
                }
                ZGSettleScheduleEnum scheduleEnum = ZGSettleScheduleEnum.getEnumByCd(Integer.parseInt(scheduleCd));
                if (scheduleEnum == null || !(ZGSettleScheduleEnum.PRE_ZF_STL_FIRST.getScheduleCd().equals(scheduleEnum.getScheduleCd())
                        || ZGSettleScheduleEnum.PRE_ZF_STL_SECOND.getScheduleCd().equals(scheduleEnum.getScheduleCd()))) {
                    throw new BaseException("参数scheduleCd不合法！");
                }
                String paySchId = request.getParameter("paySchId");
                if (StringUtils.isEmpty(paySchId)) {
                    throw new BaseException("支付表ID不能为空！");
                }
                String pInstId = request.getParameter("pInstId");
                if (StringUtils.isEmpty(pInstId)) {
                    throw new BaseException("流程实例ID不能为空！");
                }
                record.setpInstId(pInstId);
                record.setScheduleCd(scheduleEnum.getScheduleCd().toString());
                record.setSeqNum(scheduleEnum.getWeight().longValue());
                record.setDataRemark(scheduleEnum.getDataRemark());
                record.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
                record.setCreateUser(CurrentThreadContext.getCurrentUserName());
                record.setPaySchId(Long.parseLong(paySchId));
            } else {
                // 修改
                record.setId(Long.parseLong(id));
            }
            record.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
            record.setModifyUser(CurrentThreadContext.getCurrentUserName());
            record.setCompleteTime(new Date());
            int success = prjSettleOfFinInstService.modifyScheduleOtherInfo(record);
            if (success == 0) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("维护我司与资方结清金额失败！");
            }
        } catch (BaseException e) {
            BaseLogUtils.error(logger, "modifyStlAmtOther", "资金部维护我司与资方结清金额操作异常", e);
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(e.getMessage());
        } catch (Exception e) {
            BaseLogUtils.error(logger, "modifyStlAmtOther", "资金部维护我司与资方结清金额操作异常", e);
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
        }
        return result;
    }

    /**
         * 资管结清-添加来款页面
     * @param request
     * @return
     * @throws BaseException
     */
    @RequestMapping(value = "/toAddCapFundPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toAddCapFundPage(HttpServletRequest request) throws BaseException {
        BaseLogUtils.info(logger, "toAddCapFundPage", "资管结清到录入来款页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("project/settleOfFinaInst/settleCapFundAdd");
        // 业务主键：结清->支付表ID
        String dataId = request.getParameter("dataId");
        // 项目ID
        String prjId = request.getParameter("prjId");
        String isMdfPaySch = request.getParameter("isMdfPaySch");
        if (StringUtils.isEmpty(dataId) || StringUtils.isEmpty(prjId)) {
            BaseLogUtils.info(logger, "toAddCapFundPage", "资管结清到录入来款页面Error:业务主键或项目ID为空.", CurrentThreadContext.getCurrentUserName());
            return mav;
        }
        Long zfPaySchId = Long.parseLong(dataId);

        //查询项目信息
        PrjBscInfoVO prjBscInfoVO = this.prjBscInfoService.selectById(Long.parseLong(prjId));
        if (prjBscInfoVO == null) {
            BaseLogUtils.info(logger, "toAddCapFundPage", "到结清录入来款页面,未找到支付表[" + dataId + "]对应项目信息.", CurrentThreadContext.getCurrentUserName());
            return mav;
        }
        PrjPrdPaySchMQueryCondition prjPrdPaySchMQueryCondition = new PrjPrdPaySchMQueryCondition();
        prjPrdPaySchMQueryCondition.setPrjId(Long.parseLong(prjId));
        List<PrjPrdPaySchMDTO> prjPrdPaySchMDTOS = prjPrdPaySchMApiService.selectListByPrjId(prjPrdPaySchMQueryCondition);
        if (CollectionUtils.isEmpty(prjPrdPaySchMDTOS)) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, "支付表信息不存在！");
        }
        // 资方支付表 1
        PrjPrdPaySchMDTO paySchMDTO = null;
        // 我司支付表列表 N
        List<Long> ourCompnayPaySchIds = Lists.newArrayListWithCapacity(prjPrdPaySchMDTOS.size() - 1);
        for (PrjPrdPaySchMDTO prjPrdPaySchMDTO : prjPrdPaySchMDTOS) {
            if (prjPrdPaySchMDTO.getIsSqBiz() == BaseConstant.IS_YESNO_YES) {
                ourCompnayPaySchIds.add(prjPrdPaySchMDTO.getId());
            } else {
                paySchMDTO = prjPrdPaySchMDTO;
            }
        }
        if (paySchMDTO == null) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, "资方支付表信息不存在！");
        }
        if (CollectionUtils.isEmpty(ourCompnayPaySchIds)) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, "我司支付表信息不存在！");
        }

        if ("1".equals(isMdfPaySch)) {
            boolean flag = this.capFundService.modifyPaySchById(zfPaySchId);
            BaseLogUtils.info(logger, "toAddCapFundPage", "到结清录入来款页面前修改支付表==" + flag);
        }

        BaseLogUtils.info(logger, "toAddCapFundPage", "到结清录入来款页面");
        CapFundVO fundVO = new CapFundVO();
        fundVO.setRelationPayId(zfPaySchId);//资金管理关联业务ID
        fundVO.setIdentifyOperator(CurrentThreadContext.getCurrentUserId());//认款人ID
        fundVO.setIdentifyOperatorNm(CurrentThreadContext.getCurrentUserName());//认款人名称
        fundVO.setIdentifyTime(new Date());//认款时间 add时会修改
        fundVO.setAcceptName(InsuranceConstant.CODE_FC_ACCEPT_ACCOUNT_NM);//收款账户
        fundVO.setAcceptCode(InsuranceConstant.CODE_FC_ACCEPT_ACCOUNT_CD);//收款账号
        fundVO.setPaySchNo(paySchMDTO.getPaySchNo());
        fundVO.setCstId(paySchMDTO.getCstId());
        fundVO.setCstNm(prjBscInfoVO.getCstNm());
        fundVO.setFundBelongOrgCd(prjBscInfoVO.getBuOrgCd());
        fundVO.setComeName(prjBscInfoVO.getCstNm());
        //交易日期与实际到账日期默认流程发起时间
        Date flowStartTm = this.capFundService.getFlowStartTime(zfPaySchId, CapitalConstant.CODE_BIZ_TYP_CD_3);
        if (null != flowStartTm) {
            fundVO.setAcceptDate(DateUtils.formatDate(flowStartTm, DateUtils.YYYY_MM_DD));
            fundVO.setAcceptActualDate(DateUtils.formatDate(flowStartTm, DateUtils.YYYY_MM_DD));
            fundVO.setAcceptDates(DateUtils.formatDateToString(fundVO.getAcceptDate(), DateUtils.YYYY_MM_DD));
            fundVO.setAcceptActualDates(DateUtils.formatDateToString(fundVO.getAcceptActualDate(), DateUtils.YYYY_MM_DD));
        }

        // 查询资方待分解支付表+罚息
        CapFundQueryCondition qc = new CapFundQueryCondition();
        qc.setCstId(fundVO.getCstId());
        qc.setPaySchId(paySchMDTO.getId());
        //qc.setPaySchIdList(ourCompnayPaySchIds);
        if (null != flowStartTm) {
            qc.setAcceptActualDate(DateUtils.formatDate(flowStartTm, DateUtils.YYYY_MM_DD));
        }
        List<PrjPrdPaySchDVO> voList = this.capFundService.searchPaySchDList(qc);
        if (CollectionUtils.isNotEmpty(voList)) {
            mav.addObject("paySchList", JSON.toJSONString(voList));
        }

        //结清时间
        PrjPrdDtlQueryCondition dtlQueryCondition = new PrjPrdDtlQueryCondition();
        dtlQueryCondition.setPaySchId(ourCompnayPaySchIds.get(0));
        List<PrjPrdDtlVO> prdDtlVOList = this.prjPrdDtlService.selectList(dtlQueryCondition);
        if (CollectionUtils.isNotEmpty(prdDtlVOList)) {
            PrjPrdDtlVO prjPrdDtlVO = prdDtlVOList.get(0);
            if (null != prjPrdDtlVO.getStlDt()) {
                mav.addObject("stlDt", DateUtils.formatDateToString(prjPrdDtlVO.getStlDt(), DateUtils.YYYY_MM_DD));
            }
        }
        if (null != fundVO && fundVO.getAcceptDate() != null) {
            fundVO.setAcceptDates(DateUtils.formatDateToString(fundVO.getAcceptDate(), DateUtils.YYYY_MM_DD));
        }
        if (null != fundVO && fundVO.getAcceptActualDate() != null) {
            fundVO.setAcceptActualDates(DateUtils.formatDateToString(fundVO.getAcceptActualDate(), DateUtils.YYYY_MM_DD));
        }

        List<KeyValueVO> orgList = this.cstBscInfoService.searchBusinessOrgList();
        mav.addObject("fundBelongOrgCdList", JSON.toJSONString(orgList));

        mav.addObject("paySchId", paySchMDTO.getId());
        // 查询我司和资方的保证金列表使用
        ourCompnayPaySchIds.add(paySchMDTO.getId());
        mav.addObject("ourPaySchIds", JSON.toJSONString(ourCompnayPaySchIds));
        mav.addObject("cstId", fundVO.getCstId());
        mav.addObject("prjId", prjId);
        mav.addObject("capFundVO", fundVO);
        return mav;
    }

    /**
     * 修改结清时间
     * @param request
     * @return
     */
    @RequestMapping(value = "/modifyStlDt.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object modifyStlDt(HttpServletRequest request) {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        try {
            String prjId = request.getParameter("prjId");
            String stlDt = request.getParameter("stlDt");
            if (StringUtils.isEmpty(prjId)) {
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "项目ID不能为空！");
            }
            if (StringUtils.isEmpty(stlDt)) {
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "结清时间不能为空！");
            }

            boolean flag = prjSettleOfFinInstService.modifyStlDt(Long.parseLong(prjId), stlDt);
            if (!flag) {
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "操作失败！");
            }
        } catch (BaseException e) {
            BaseLogUtils.error(logger, "modifyStlAmtOther", "修改结清时间操作异常", e);
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(e.getMessage());
        } catch (Exception e) {
            BaseLogUtils.error(logger, "modifyStlAmtOther", "修改结清时间操作异常", e);
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
        }
        return result;
    }

    /**
     * 查询资管接口进度列表数据
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/zfScheduleList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object selectScheduleListOfZG(HttpServletRequest request) {
        String paySchId = request.getParameter("paySchId");
        // flow为1，代表已经发起了流程
        String flow = request.getParameter("flow");
        // 流程实例ID
        String pInstId = request.getParameter("pInstId");

        List<CapCstStmScheduleDTO> list = Lists.newArrayList();
        if (StringUtils.isEmpty(paySchId) || StringUtils.isEmpty(flow)) {
            ListPageVO<CapCstStmScheduleDTO> listPage = new ListPageVO<>(list, 0);
            return listPage;
        }

        list = prjSettleOfFinInstService.selectScheduleListOfZG(Long.parseLong(paySchId), pInstId);
        ListPageVO<CapCstStmScheduleDTO> listPage = new ListPageVO<>(list, list.size());
        return listPage;
    }

    /**
     * 重新调用资方接口获取结清信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/reacquire.do", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object reacquire(HttpServletRequest request) {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        try {
            String prjId = request.getParameter("prjId");
            String paySchId = request.getParameter("paySchId");
            String scheduleCd = request.getParameter("scheduleCd");
            if (StringUtils.isEmpty(prjId)) {
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "接口请求参数：项目ID不能为空！");
            }
            if (StringUtils.isEmpty(paySchId)) {
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "接口请求参数：支付表ID不能为空！");
            }
            if (StringUtils.isEmpty(scheduleCd)) {
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "接口请求参数：申请进度编码不能为空！");
            }
            ZGSettleScheduleEnum scheduleEnum = ZGSettleScheduleEnum.getEnumByCd(Integer.parseInt(scheduleCd));
            if (scheduleEnum == null || !(ZGSettleScheduleEnum.PRE_ZF_STL_FIRST.getScheduleCd().equals(scheduleEnum.getScheduleCd())
                    || ZGSettleScheduleEnum.PRE_ZF_STL_SECOND.getScheduleCd().equals(scheduleEnum.getScheduleCd()))) {
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "接口请求参数：申请进度编码不是合法数据！");
            }
            Long stlAmt = prjSettleOfFinInstService.reacquire(Long.parseLong(prjId), Long.parseLong(paySchId), scheduleEnum);
            if (stlAmt == null) {
                result.setSuccess(2);
                result.setInfo("获取失败，请稍后重试。");
            } else {
                result.setInfo("获取成功，我司与资方当前结清金额为：￥" + DecimalUtils.convertFenToYuan(stlAmt));
            }
        } catch (BaseException e) {
            BaseLogUtils.error(logger, "reacquire", "重新调用资方接口获取结清信息异常", e);
            result.setSuccess(2);
            result.setInfo(e.getMessage());
        } catch (Exception e) {
            BaseLogUtils.error(logger, "reacquire", "重新调用资方接口获取结清信息异常", e);
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
        }
        return result;
    }
}
